<template>
  <div>
    <!-- 搜索工作栏 -->
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="租赁状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择租赁状态"
            clearable
            class="!w-240px"
          >
            <el-option label="全部" value="" />
            <el-option label="进行中" value="1" />
            <el-option label="已完成" value="2" />
            <el-option label="已取消" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁商品" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="租赁时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-tabs v-model="queryParams.tabType" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="item in tabsData"
          :key="item.type"
          :label="item.name + '(' + item.count + ')'"
          :name="item.type"
        />
      </el-tabs>
      
      <el-table v-loading="loading" :data="list" stripe>
        <el-table-column label="租赁订单号" align="center" prop="orderNo" width="180" />
        <el-table-column label="商品信息" align="center" width="300">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-image
                :src="row.productImage"
                class="h-40px w-40px flex-none rounded"
                fit="cover"
              />
              <div class="ml-10px">
                <div class="text-14px font-medium">{{ row.productName }}</div>
                <div class="text-12px text-gray-500">{{ row.productSpec }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="租赁用户" align="center" prop="userName" width="120" />
        <el-table-column label="租赁时长" align="center" width="120">
          <template #default="{ row }">
            {{ row.leaseDays }}天
          </template>
        </el-table-column>
        <el-table-column label="租赁金额" align="center" width="120">
          <template #default="{ row }">
            ¥{{ (row.leaseAmount / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="押金" align="center" width="120">
          <template #default="{ row }">
            ¥{{ (row.deposit / 100).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="租赁状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="开始时间"
          align="center"
          prop="startTime"
          width="180"
          :formatter="dateFormatter"
        />
        <el-table-column
          label="结束时间"
          align="center"
          prop="endTime"
          width="180"
          :formatter="dateFormatter"
        />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDetail(row.id)">
              详情
            </el-button>
            <el-button 
              v-if="row.status === 1" 
              link 
              type="warning" 
              @click="handleReturn(row.id)"
            >
              归还
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 租赁详情对话框 -->
    <el-dialog v-model="detailVisible" title="租赁详情" width="800px">
      <div v-if="currentLease">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentLease.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="租赁状态">
            <el-tag :type="getStatusTagType(currentLease.status)">
              {{ getStatusText(currentLease.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ currentLease.productName }}</el-descriptions-item>
          <el-descriptions-item label="商品规格">{{ currentLease.productSpec }}</el-descriptions-item>
          <el-descriptions-item label="租赁用户">{{ currentLease.userName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentLease.userPhone }}</el-descriptions-item>
          <el-descriptions-item label="租赁时长">{{ currentLease.leaseDays }}天</el-descriptions-item>
          <el-descriptions-item label="租赁金额">¥{{ (currentLease.leaseAmount / 100).toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="押金">¥{{ (currentLease.deposit / 100).toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDate(currentLease.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDate(currentLease.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentLease.createTime) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'

defineOptions({ name: 'LeaseManagement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const detailVisible = ref(false) // 详情对话框显示状态
const currentLease = ref(null) // 当前查看的租赁记录

// tabs 数据
const tabsData = ref([
  {
    name: '全部',
    type: '',
    count: 0
  },
  {
    name: '进行中',
    type: '1',
    count: 0
  },
  {
    name: '已完成',
    type: '2',
    count: 0
  },
  {
    name: '已取消',
    type: '3',
    count: 0
  }
])

const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  tabType: '',
  status: '',
  productName: '',
  createTime: []
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 模拟数据，实际应该调用API
    const mockData = {
      list: [
        {
          id: 1,
          orderNo: 'LS202412060001',
          productName: '奔驰C200',
          productSpec: '白色/自动挡',
          productImage: 'https://via.placeholder.com/40x40',
          userName: '张三',
          userPhone: '13800138000',
          leaseDays: 7,
          leaseAmount: 70000, // 分为单位
          deposit: 50000,
          status: 1,
          startTime: '2024-12-01 10:00:00',
          endTime: '2024-12-08 10:00:00',
          createTime: '2024-12-01 09:30:00'
        },
        {
          id: 2,
          orderNo: 'LS202412060002',
          productName: '宝马X3',
          productSpec: '黑色/自动挡',
          productImage: 'https://via.placeholder.com/40x40',
          userName: '李四',
          userPhone: '13900139000',
          leaseDays: 3,
          leaseAmount: 45000,
          deposit: 30000,
          status: 2,
          startTime: '2024-11-28 14:00:00',
          endTime: '2024-12-01 14:00:00',
          createTime: '2024-11-28 13:30:00'
        }
      ],
      total: 2
    }
    
    list.value = mockData.list
    total.value = mockData.total
    
    // 更新tabs统计
    tabsData.value[0].count = mockData.total
    tabsData.value[1].count = mockData.list.filter(item => item.status === 1).length
    tabsData.value[2].count = mockData.list.filter(item => item.status === 2).length
    tabsData.value[3].count = mockData.list.filter(item => item.status === 3).length
    
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** tab 切换 */
const handleTabClick = () => {
  queryParams.value.status = queryParams.value.tabType
  handleQuery()
}

/** 查看详情 */
const openDetail = (id: number) => {
  const lease = list.value.find(item => item.id === id)
  if (lease) {
    currentLease.value = lease
    detailVisible.value = true
  }
}

/** 处理归还 */
const handleReturn = async (id: number) => {
  try {
    await message.confirm('确认归还该租赁商品吗？')
    // 这里应该调用归还API
    message.success('归还成功')
    await getList()
  } catch {}
}

/** 获取状态标签类型 */
const getStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'warning'
    case 2: return 'success'
    case 3: return 'danger'
    default: return 'info'
  }
}

/** 获取状态文本 */
const getStatusText = (status: number) => {
  switch (status) {
    case 1: return '进行中'
    case 2: return '已完成'
    case 3: return '已取消'
    default: return '未知'
  }
}

/** 格式化日期 */
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  return dateStr
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.spu-table-expand {
  padding-left: 42px;

  .el-form-item {
    margin-right: 0;
    margin-bottom: 8px;
    width: 50%;
  }
}
</style>
